package com.jhws.business.local.service;

import com.jhws.business.comm.bo.TblBuildingDimBo;
import com.jhws.business.comm.service.ITblBuildingDimService;
import com.jhws.sys.params.bo.SysParam;
import com.jhws.sys.params.bo.SysParamConstant;
import com.jhws.sys.params.service.SysParamService;
import com.jhws.util.LogHelper;
import com.jhws.util.jsonUtil;
import com.jhws.util.net.JhHttpClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class CommSynchService {
    @Resource
    private SysParamService paramService;
    @Resource
    private ITblBuildingDimService buildingDimService;

    public void mergeComm(String serverUrl, String commCode, Map<String, String> headers) throws Exception {
        Long timeStamp = (long) -1;
        SysParam param = paramService.getParam("timeStampLocalSrvBuilding");
        if (param != null) {
            timeStamp = Long.valueOf(param.getValue());
        }

        int count = buildingDimService.getCountByComm(commCode);
        if (count == 0)
            timeStamp = (long) -1;
        JhHttpClient hp = new JhHttpClient();
        LogHelper.e("----------------------->   localServerUrl   "+serverUrl);
        String str = hp.get(serverUrl + "api/LocalSrv/updateBuildings?commCode=" + commCode + "&timeStamp=" + timeStamp, headers);
        LogHelper.e("----------------------->      "+str);
        if ((Integer) jsonUtil.getKeyFromJsonObject(str, "ret_code") == -1) {
            LogHelper.getLogger().debug("data error");
            return;
        }
        LogHelper.getLogger().debug("get data " + str);
        List<TblBuildingDimBo> retList = jsonUtil.getBeansFromJsonDataObject(str, "list", TblBuildingDimBo.class);
        for (TblBuildingDimBo bo : retList) {
            bo.setBuildingCode(null);
            buildingDimService.save(bo);
        }

        Integer tStamp = jsonUtil.getKeyFromJsonDataObject(str, "timeStamp");
        if (tStamp == -1)
            return;

        if (param == null) {
            param = new SysParam();
            param.setName("timeStampLocalSrvBuilding");
        }

        param.setValue(tStamp.toString());
        param.setParent(SysParamConstant.PARAM_TYPE_LOCAL_SERVER);
        paramService.save(param);
    }
}
